package com.ibeeking.found.uaa.b.config.auth.sms;

import com.ibeeking.found.uaa.b.config.auth.token.AbstractCustomTokenGranter;
import com.ibeeking.found.uaa.b.model.TenantUserDetails;
import com.ibeeking.found.uaa.b.service.ITenantUserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

public class SmsCodeTokenGranter extends AbstractCustomTokenGranter {

    private static final String GRANT_TYPE = "sms_code";
    private static final String PHONE_PARAM = "phone";
    private static final String CODE_PARAM = "code";
    private static final String KEY_PARAM = "key";

    private final ITenantUserDetailsService userDetailsServiceImpl;

    public SmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsServiceImpl, OAuth2RequestFactory requestFactory, ITenantUserDetailsService userDetailsServiceImpl) {
        super(tokenServices, clientDetailsServiceImpl, requestFactory, GRANT_TYPE);
        this.userDetailsServiceImpl = userDetailsServiceImpl;
    }

    @Override
    protected TenantUserDetails getUserDetails(Map<String, String> parameters) {
        String phone = parameters.get(PHONE_PARAM);
        String smsCode = parameters.get(CODE_PARAM);
        String key = parameters.get(KEY_PARAM);
        return userDetailsServiceImpl.loadUserByPhoneAndSmsCode(phone, smsCode,key);
    }
}
